import { native } from "cc";
import NativeClient, { NativeClientIns, NCAPIStructure } from "./NativeClient";

const NativeConfig = {
    class_ios: 'Ww_MessageManager_wW',
    request_call: 'Ww_callNative_wWWithName:data:',

    class_creator: 'Ww_iOSClient_wW',
    response_call: 'Ww_response_wW'
}

/** 原生端行为模拟 */
class iOSClient extends NativeClientIns {
	private static receive_call_list: Array<(api: string, response: Awaited<NCAPIStructure<any, any>['response']>) => void> = [];

	public callStaticMethod(api: string, request: NCAPIStructure<any, any>['request']) {
		iOSClient.request(api, request);
	}

	public onReceiveMessage(callback: (api: string, response: Awaited<NCAPIStructure<any, any>['response']>) => void) {
		iOSClient.receive_call_list.push(callback);
	}

	private static request(api: string, request: NCAPIStructure<any, any>['request']) {
		native.reflection.callStaticMethod(NativeConfig.class_ios, NativeConfig.request_call, api, JSON.stringify(request));
	}

	private static response(api: string, json_string: string) {
		let response = JSON.parse(json_string) as Awaited<NCAPIStructure<any, any>['response']>;
		iOSClient.receive_call_list.forEach(callback => callback(api, response));
	}
}

NativeClient.initClient(platform=>{
	if(platform=='ios'){
		Reflect.set(iOSClient, NativeConfig.response_call, Reflect.get(iOSClient, 'response'))
		Reflect.set(window ?? globalThis, NativeConfig.class_creator, iOSClient);
		return new iOSClient();
	}else{
		return void 0;
	}
});
